package com.ydl.shopping.utils.ip;

import com.ydl.shopping.utils.spring.SpringUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * IP归属地工具类
 * 
 * @author 林武泰
 */
@Component
public class AddressUtil
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

    private Searcher searcher;

    public String getIpAddress(String ip) {
        // 获取配置文件ipdb包路径
        String ipdbPath = SpringUtil.getRequiredProperty("my.ipdbPath");
        // 获取配置文件ipdb包名
        String ipdbName = SpringUtil.getRequiredProperty("my.ipdbName");

        String ipdbFile = ipdbPath + ipdbName;
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "内网IP";
        }
        if (searcher == null) {
            try {
                File file = new File(ipdbFile);
                String path = file.getPath();
                searcher = Searcher.newWithFileOnly(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String region = null;
        String errMsg;

        try {
            region = searcher.search(ip);
            String[] split = region.split("\\|");
            // 获取国家
            String nation = split[0];
            if (nation.equals("0")) {
                nation = "";
            }
            // 获取省份
            String province = split[2];
            if (province.equals("0")) {
                province = "";
            }
            // 获取城市
            String city = split[3];
            if (city.equals("0")) {
                city = "";
            }
            log.info("获取IP {} 归属地为：{}", ip, region);
            region = String.format("%s %s%s", nation, province, city);
        } catch (Exception e) {
            errMsg = e.getMessage();
            if (errMsg != null && errMsg.length() > 256) {
                errMsg = errMsg.substring(0, 256);
            }
            log.error("获取IP {} 归属地出现异常：{}", ip, errMsg);
             e.printStackTrace();
        }
        return region;
    }
}
